package com.dxd.servlet;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dxd.constant.ErrorCodeConstant;
import com.dxd.entity.ReturnBean;
import com.dxd.utils.JSONTools;

/**
 * 拦截所有带有auth的请求
 * 
 * @author pppcar
 *
 */
public class LoginFilter implements Filter {

	private static final Logger LOG = LoggerFactory.getLogger(LoginFilter.class);

	FilterConfig config;

	public void destroy() {
		this.config = null;
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {

		try {
			// 将请求转换成HttpServletRequest 请求
			HttpServletRequest request = (HttpServletRequest) arg0;
			HttpServletResponse response = (HttpServletResponse) arg1;

			// 获取请求地址和项目名称
			String requestUrl = request.getServletPath();
			String contextPath = request.getContextPath();
			LOG.info("拦截请求url：{},拦截请求ip地址:{}", requestUrl, request.getRemoteAddr());

			// 用来判断请求是不是ajax请求
			String XRequested = request.getHeader("X-Requested-With");

			if (requestUrl.indexOf("admin") >= 0) {

				// 后端请求路径中包含"admin"字符串，表示需要登录则验证登录信息，获取登录session,这里只是简单的判断，并没有真正的验证登录信息是否正确
				Object loginSession = request.getSession().getAttribute("loginSession");
				if (loginSession == null || "".equals(loginSession)) {

					LOG.error("后端session过期或未登录，请重新登录");
					// 如果请求是ajax请求
					if ("XMLHttpRequest".equals(XRequested)) {
						ReturnBean returnBean = ReturnBean.returnBeanBuild();
						returnBean.setReturnCode(ErrorCodeConstant.IS_NOT_LOGIN).setReturnMsg("登录过后才能操作");
						response.getWriter().write(JSONTools.obj2json(returnBean));
						return;
					}
					response.sendRedirect(contextPath + "/user/userInfo");

				} else {
					arg2.doFilter(arg0, arg1);
				}

			} else if (requestUrl.indexOf("swzl") >= 0) {

				// 前端请求路径中包含'swzl'字符串，则拦截，获取登录session,这里只是简单的判断，并没有真正的验证登录信息是否正确
				Object loginSession = request.getSession().getAttribute("swzlUser");
				String url = contextPath + "/swzl/userInfo?type=goLogin";
				if (loginSession == null || "".equals(loginSession)) {

					LOG.error("前端session过期或未登录,请重新登录");
					// 如果请求是ajax请求
					if ("XMLHttpRequest".equals(XRequested)) {
						ReturnBean returnBean = ReturnBean.returnBeanBuild();
						returnBean.setReturnCode(ErrorCodeConstant.IS_NOT_LOGIN).setReturnMsg("登录过后才能操作");
						response.getWriter().write(JSONTools.obj2json(returnBean));
						return;
					}
					response.sendRedirect(url);

				} else {
					arg2.doFilter(arg0, arg1);
				}

			} else {
				// 所有不需要登录的请求，直接通过
				arg2.doFilter(arg0, arg1);

			}
		} catch (Exception e) {
			LOG.error("拦截器异常");
			e.printStackTrace();
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		this.config = arg0;
	}

}